using System;
using System.Threading;

namespace SimpleServiceBus.Bus.MessageManagement.Callbacks
{
    public class BusAsyncResult : IAsyncResult
    {
        private readonly AsyncCallback _callback;
        private readonly CompletionResult _result;
        private readonly ManualResetEvent _sync;
        private volatile bool _completed;

        public BusAsyncResult(AsyncCallback callback, object state)
        {
            _callback = callback;
            _result = new CompletionResult();
            _result.State = state;
            _sync = new ManualResetEvent(false);
        }

        #region IAsyncResult Members

        public object AsyncState
        {
            get { return _result; }
        }

        public WaitHandle AsyncWaitHandle
        {
            get { return _sync; }
        }

        public bool CompletedSynchronously
        {
            get { return false; }
        }

        public bool IsCompleted
        {
            get { return _completed; }
        }

        #endregion

        public void Complete(int errorCode, object message)
        {
            _result.ErrorCode = errorCode;
            _result.Message = message;
            _completed = true;
            _sync.Set();

            if (_callback != null)
                _callback(this);
        }
    }
}